import Vue from "vue";
import Vuex from "vuex";

import aaa from 'vuex-persistedstate'
Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    // 存储用户名
    usersInfo: {},
    // 收藏存储当前数据
    collectData: [],
    // 存储购物车的数据
    shopping: [],
    // 存储订单数据
    OredeData: [],
  },
  mutations: {

    // 存储用户名
    userName(state, name) {
      state.usersInfo = name
      // console.log(state.usersInfo);
    },

    // 删除用户名
    delUser(state) {
      state.usersInfo = ''
    },

    // 收藏的当前商品数据+去重
    collectEvent(state, obj) {
      // console.log(obj.product_id);
      // state.collectData = obj
      // console.log(state.collectData);
      // state.collectData.push(obj)
      if (state.collectData.findIndex(i => { i.product_id == obj.product_id }) > -1) {
        state.collectData(state.collectData[state.collectData.findIndex(i => { i.product_id == obj.product_id })], 1)
      } else {
        state.collectData.push(...obj)
      }
    },

    // 删除收藏
    delGoods(state, id) {
      state.collectData.forEach((item, index) => {
        if (item.product_id == id) {
          state.collectData.splice(index, 1)
        }
      })
    },

    // 购物车数据
    shoppingData(state, obj) {
      state.shopping.push(...obj)
      console.log('购物车---》', state.shopping);
    },

    // 删除购物车数据
    delShopping(state, id) {
      console.log(id);
      state.shopping.forEach((item, index) => {
        if (item.product_id == id) {
          state.shopping.splice(index, 1)
        }
      })
    },

    // 保存数据
    orderEvent(state, obj) {
      // console.log(obj);
      state.OredeData.push(...obj)
      console.log('订单列表---》', state.OredeData);
    },
  },
  actions: {},
  modules: {},
  getters: {
    // 计算总价
    cont(state) {
      var ShoppingPrice = 0;
      state.shopping.forEach((item) => {
        return ShoppingPrice += item.product_price * item.product_sales;
      });
      return ShoppingPrice;
    },

    // 计算数量
    goodsNum(state) {
      var num = 0;
      state.shopping.forEach((item) => {
        return num += item.product_sales;
      });
      return num;
    },
  },
  plugins: [aaa()],//引入插件
});
